﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AppManagement.BusManagers
{
    #region Using
    using DevComponents.DotNetBar;
    using AppManagement.Helpers;
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.UsersManager;
    #endregion

    /// <summary>
    ///  manage loai don vi corresponding with menus in app
    /// </summary>
    public partial class FrmQuanLyDichVu: Office2007Form
    {
        //  event handler to transfer data to other forms
        public EventHandler Handler { get; set; }
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaNhomDV;
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaBP;
        // ---------------- E -----------------

        public FrmQuanLyDichVu(bool EnableBtnChon = false)
        {
            InitializeComponent();
            InitHiddenFields();
            btnChon.Enabled = EnableBtnChon;
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaNhomDV = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaNhomDV",
                Text = ""
            };
            txtMaNhomDV.Visible = false;

            // Add a new textbox
            txtMaBP = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaBP",
                Text = ""
            };
            txtMaBP.Visible = false;
        }

        private void FrmQuanLyDichVu_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionAdd())
            {
                LoadData();
                EraseTextboxes();
                MessageBox.Show("Lưu dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Lưu dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBox.Show("Bạn có chắc chắn xóa dòng này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ActionDelete())
                {
                    LoadData();
                    EraseTextboxes();
                    MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionUpdate())
            {
                LoadData();
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            EraseTextboxes();
        }

        private void dtgvDataList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;
            txtMaDichVu.Text = dtgvDataList.SelectedRows[0].Cells["MaDV"].Value.ToString(); ;

            var item = DichVuRepository.SelectByID(txtMaDichVu.Text);
            LoadDetailInfo(item);
        }

        public void LoadDetailInfo(DichVu item)
        {
            txtTenDichVu.Text = item.TenDV == null ? "" : item.TenDV;
            txtPhiDichVu.Text = item.PhiDV == null ? "" : String.Format("{0:#,##0;Nothing}", item.PhiDV);
            txtDiaChiGioiThieu.Text = item.DiaChiGioiThieu == null ? "" : item.DiaChiGioiThieu;
            txtDTGioiThieu.Text = item.DienThoaiGioiThieu == null ? "" : item.DienThoaiGioiThieu;
            txtGhiChu.Text = item.GhiChu == null ? "" : item.GhiChu;

            txtMaNhomDV.Text = item.MaNhomDV == null ? "" : item.MaNhomDV;
            txtNhomDV.Text = item.MaNhomDV == null ? "" : item.NhomDichVu.TenNhomDV;
            txtMaBP.Text = item.MaBP == null ? "" : item.MaBP;
            txtBP.Text = item.MaBP == null ? "" : item.BenhPham.TenBP;
            ckbxKhamTaiCho.Checked = item.TaiCho.Value;
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.CHOOSING, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var id = txtMaDichVu.Text;
            var dichvu = DichVuRepository.SelectByID(id);
            TransferDataInfo(this, new TransferSimpleDataEvent(id + "#" + dichvu.TenDV));
        }

        /// <summary>
        /// Load data from DB
        /// </summary>
        private void LoadData()
        {
            var lstItem = DichVuRepository.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("MaDV");
            dt.Columns.Add("TenDV");
            dt.Columns.Add("NhomDV");
            dt.Columns.Add("PhiDV");
            dt.Columns.Add("TaiCho");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaDV, lstItem[i].TenDV, lstItem[i].NhomDichVu.TenNhomDV, String.Format("{0:#,##0;Nothing}", lstItem[i].PhiDV), lstItem[i].TaiCho.Value);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
        {
            // Mode update -> checking MaDichVu is exists on textbox
            if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE || mode == EnumUpdateMode.CHOOSING)
            {
                if (txtMaDichVu.Text == "")
                {
                    errorText = "Vui lòng chọn dịch vụ";
                    return false;
                }
            }
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtTenDichVu.Text == "")
                {
                    errorText = "Vui lòng nhập tên dịch vụ";
                    return false;
                }
                if (txtMaNhomDV.Text == "")
                {
                    errorText = "Vui lòng chọn nhóm dịch vụ";
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var item = new DichVu
                {
                    MaDV = txtMaDichVu.Text,
                    TenDV = txtTenDichVu.Text,
                    GhiChu = txtGhiChu.Text,
                    TaiCho = ckbxKhamTaiCho.Checked
                };

                UpdateForeignKeys(item);

                if (!DichVuRepository.Insert(item))
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtMaDichVu.Text = "";
            txtTenDichVu.Text = "";
            txtPhiDichVu.Text = "";
            txtDiaChiGioiThieu.Text = "";
            txtDTGioiThieu.Text = "";
            txtGhiChu.Text = "";

            txtMaNhomDV.Text = "";
            txtNhomDV.Text = "";
            txtMaBP.Text = "";
            txtBP.Text = "";
            ckbxKhamTaiCho.Checked = false;
            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Update item with specificed ID
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = DichVuRepository.SelectByID(txtMaDichVu.Text);
                item.TenDV = txtTenDichVu.Text;
                item.GhiChu = txtGhiChu.Text;
                item.TaiCho = ckbxKhamTaiCho.Checked;

                UpdateForeignKeys(item);

                return DichVuRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        public void UpdateForeignKeys(DichVu item)
        {
            if (txtPhiDichVu.Text != "")
            {
                item.PhiDV = long.Parse(txtPhiDichVu.Text.Replace(",", ""));
            }
            if (ckbxKhamTaiCho.Checked)
            {
                item.DiaChiGioiThieu = txtDiaChiGioiThieu.Text;
                item.DienThoaiGioiThieu = txtDTGioiThieu.Text;
            }
            if (txtMaNhomDV.Text != "")
            {
                item.MaNhomDV = txtMaNhomDV.Text;
            }
            if (txtMaBP.Text != "")
            {
                item.MaBP = txtMaBP.Text;
            }
        }

        /// <summary>
        /// Delete item with specified ID
        /// </summary>
        /// <returns></returns>
        private bool ActionDelete()
        {
            try
            {
                return DichVuRepository.Delete(txtMaDichVu.Text);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///  function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, TransferSimpleDataEvent e)
        {
            this.Close();
            this.Handler(this, e);
        }

        private void ckbxKhamTaiCho_CheckedChanged(object sender, EventArgs e)
        {
            txtDiaChiGioiThieu.ReadOnly = !ckbxKhamTaiCho.Checked;
            txtDTGioiThieu.ReadOnly = !ckbxKhamTaiCho.Checked;
        }

        private void btnNhomDichVu_Click(object sender, EventArgs e)
        {
            FrmQuanLyNhomDichVu frm = new FrmQuanLyNhomDichVu(true);
            frm.Handler += GetNhomDichVu;
            frm.ShowDialog();
        }

        public void GetNhomDichVu(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaNhomDV.Text = comp[0];
            txtNhomDV.Text = comp[1];
        }

        private void btnChonBenhPham_Click(object sender, EventArgs e)
        {
            FrmQuanLyBenhPham frm = new FrmQuanLyBenhPham(true);
            frm.Handler += GetBenhPham;
            frm.ShowDialog();
        }

        public void GetBenhPham(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaBP.Text = comp[0];
            txtBP.Text = comp[1];
        }

        // This variable is used to end changing on textbox
        private bool endChange = false;
        private void txtPhiDichVu_TextChanged(object sender, EventArgs e)
        {
            if (endChange)
            {
                endChange = false;
                this.txtPhiDichVu.SelectionStart = this.txtPhiDichVu.Text.Length;
                return;
            }
            if (txtPhiDichVu.Text.Length > 0)
            {
                var strOrigin = txtPhiDichVu.Text.Replace(",", "");
                var strFormated = String.Format("{0:#,##0;Nothing}", long.Parse(strOrigin));
                if (strOrigin != strFormated)
                {
                    endChange = true;
                    this.txtPhiDichVu.Text = strFormated;
                }
            }
        }

        private void txtPhiDichVu_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Only allow type number
            if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back)
            {
                e.Handled = true;
            }
        }

        private void btnChiSo_Click(object sender, EventArgs e)
        {
            if (txtMaDichVu.Text != "")
            {
                FrmCapNhatChiSo frm = new FrmCapNhatChiSo(txtMaDichVu.Text);
                frm.ShowDialog();
            }
        }
    }
}